package com.luming.ethtran.service.impl;

import com.luming.ethtran.domain.Result;
import com.luming.ethtran.domain.SysUser;
import com.luming.ethtran.mapper.SysUserMapper;
import com.luming.ethtran.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author Luming
 * @Date 2025/3/24 18:23
 * @Description:
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Override
    public Result updateInfo(SysUser user) {
        Result result = new Result<>();
        
        // 查询用户是否存在
        SysUser existingUser = sysUserMapper.selectById(user.getUserId());
        if (existingUser == null) {
            result.setCode(500);
            result.setMsg("用户不存在");
            return result;
        }
        
        // 更新邮箱和手机号
        existingUser.setEmail(user.getEmail());
        existingUser.setPhone(user.getPhone());
        existingUser.setUpdateTime(new Date());
        
        int update = sysUserMapper.updateById(existingUser);
        if (update > 0) {
            result.setCode(200);
            result.setMsg("个人信息修改成功");
        } else {
            result.setCode(501);
            result.setMsg("个人信息修改失败");
        }
        return result;
    }
    
    @Override
    public Result updatePassword(Long userId, String oldPassword, String newPassword) {
        Result result = new Result<>();
        
        // 查询用户
        SysUser user = sysUserMapper.selectById(userId);
        if (user == null) {
            result.setCode(500);
            result.setMsg("用户不存在");
            return result;
        }
        
        // 校验旧密码
        if (!user.getPassword().equals(oldPassword)) {
            result.setCode(502);
            result.setMsg("旧密码错误");
            return result;
        }
        
        // 更新密码
        user.setPassword(newPassword);
        user.setUpdateTime(new Date());
        
        int update = sysUserMapper.updateById(user);
        if (update > 0) {
            result.setCode(200);
            result.setMsg("密码修改成功");
        } else {
            result.setCode(503);
            result.setMsg("密码修改失败");
        }
        return result;
    }
}
